package com.youdoneed.community.forum.service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.youdoneed.community.common.vo.PageData;
import com.youdoneed.community.forum.dao.ForumlikespointrecordMapper;
import com.youdoneed.community.forum.entity.Forumnotice;
import com.youdoneed.community.forum.vo.CommentVo;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.news.feign.NewsClient;
import com.youdoneed.news.model.CmfPostsDtlVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.youdoneed.base.application.AppException;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.forum.dao.ForumcommentMapper;
import com.youdoneed.community.forum.dao.ForummessageMapper;
import com.youdoneed.community.forum.entity.Forumcomment;
import com.youdoneed.community.forum.entity.Forummessage;
import com.youdoneed.community.forum.vo.CreateCommentVo;

import com.youdoneed.community.forum.service.ForumServciceStatic;

@Service
public class ForumcommentService {

    private final Logger logger = LoggerFactory.getLogger(ForumcommentService.class);

    @Autowired
    ForumcommentMapper forumcommentMapper;

    @Autowired
    ForummessageMapper forummessageMapper;

    @Autowired
    NewsClient newsClient;

    @Autowired
    ForumNoticeService forumNoticeService;

    @Autowired
    ForumlikespointrecordMapper forumlikespointrecordMapper;

    @Autowired
    FriendsClient friendsClient;

    @Autowired
    ForumlikespointrecordService forumlikespointrecordService;


    /**
     * 获取我的朋友对新闻的评论
     *
     * @param userId
     * @param postId
     * @return
     */
    @Transactional
    public List<Forumcomment> getFrindsCommentInNews(String postId) {

        if (!StringUtils.hasText(postId)) {
            throw new AppException("postId参数不允许为空");
        }

        try {
            List<String> listFriendsIds = friendsClient
                    .findFriendIds(1).getData().getFriendIds();
            if (null == listFriendsIds
                    || 0 == listFriendsIds.size()) {
                logger.info("listFriendsIds.size() == 0！");
                return null;
            }

            List<Forumcomment> listForumcomment = forumcommentMapper.selectFriendsNewsCmt(postId);
            if (null == listForumcomment
                    || 0 == listForumcomment.size()) {
                logger.info("listForumcomment.size() == 0！");
                return null;
            }

            Iterator<Forumcomment> iterator = listForumcomment.iterator();
            while (iterator.hasNext()) {
                Forumcomment forumcomment = iterator.next();
                if (!listFriendsIds.contains(forumcomment.getUserId())) {
                    iterator.remove();
                }
            }

            logger.info("listForumcomment.size()：" + listForumcomment.size());

            return listForumcomment;
        } catch (Exception e) {
            logger.error("保存论坛评论异常:" + e);
            return null;
        }

    }

    @Transactional
    public boolean publishForumcomment(CreateCommentVo vo) {
        if (null == vo) {
            throw new AppException("vo参数不允许为空");
        }

        if (!StringUtils.hasText(vo.getMsgType())) {
            throw new AppException("msgType参数不允许为空");
        }

        if ((ForumServciceStatic.cmtComment.equals(vo.getMsgType()))
                && (!StringUtils.hasText(vo.getParentCommentId()))) {
            throw new AppException("父评论id参数不允许为空");
        }

        if ((!StringUtils.hasText(vo.getParentCommentId()))
                && !StringUtils.hasText(vo.getMsgSourceId())) {
            throw new AppException("msgSourceId参数不允许为空");
        }

        if (!StringUtils.hasText(vo.getUserId())) {
            throw new AppException("userId参数不允许为空");
        }

        //可以仅评论图片
        if (!StringUtils.hasText(vo.getContent())) {
            if (!StringUtils.hasText(vo.getCommentPicUrl())) {
                throw new AppException("评论的内容为空！");
            }
        } else {
            /**
             * 判断文本内容长度
             */
            if (ForumServciceStatic.maxContentLength < vo.getContent().length()) {
                logger.info("文本内容超过200个字符！");
                throw new AppException("文字内容超过200个字符！");
            }
        }


        if (!StringUtils.hasText(vo.getUserNickname())) {
            throw new AppException("您还没有设置昵称哦，请先设置昵称吧~");
        }

        if (!StringUtils.hasText(vo.getUserHeadUrl())) {
            throw new AppException("您还没有设置头像哦，请先上传头像吧~");
        }


        try {
            Forumcomment forumcomment = new Forumcomment();
            //生成uuid
            forumcomment.setForumCommentId(StringUUIdUtil.getUUID());

            //设置时间
            forumcomment.setCreateDate(new Date());
            forumcomment.setCommentCount(0);
            forumcomment.setCommentDelete(0);
            if (StringUtils.hasText(vo.getCommentFromTo())) {
                forumcomment.setCommentFromTo(vo.getCommentFromTo());
            }

            if (StringUtils.hasText(vo.getCommentPicUrl())) {
                forumcomment.setCommentPicUrl(vo.getCommentPicUrl());
            }

            forumcomment.setContent(vo.getContent());
            forumcomment.setForumMsgId(vo.getMsgSourceId());
            forumcomment.setMsgType(vo.getMsgType());
            forumcomment.setLikesCount(0);

            if (StringUtils.hasText(vo.getParentCommentId())) {
                forumcomment.setParentCommentId(vo.getParentCommentId());
            }
            forumcomment.setCommentPicUrl(vo.getCommentPicUrl());
            forumcomment.setProhibit(0);
            forumcomment.setReportCount(0);
            forumcomment.setUserHeadUrl(vo.getUserHeadUrl());
            forumcomment.setUserId(vo.getUserId());
            forumcomment.setUserNickname(vo.getUserNickname());

            forumcommentMapper.insert(forumcomment);

            /**
             * 保存通知消息
             */
            Forumnotice notice = new Forumnotice();
            notice.setCreateDate(new Date());
            notice.setForumNoticeId(StringUUIdUtil.getUUID());

            notice.setNoticeUserHeadUrl(vo.getUserHeadUrl());
            notice.setNoticeUserId(vo.getUserId());
            notice.setReadStatus(0);
            notice.setNoticeUserNickname(vo.getUserNickname());
            //对应的评论数+1
            //对评论进行评论
            if (ForumServciceStatic.cmtComment.equals(vo.getMsgType())) {
                logger.info("对评论进行评论！被评论的id：" + forumcomment.getParentCommentId());
                //评论的评论数+1
                Forumcomment parentForumcomment = forumcommentMapper.selectByPrimaryKey(forumcomment.getParentCommentId());
                if (null == parentForumcomment) {
                    logger.info("未找到对应的父评论！parentCommentId:" + forumcomment.getParentCommentId());
                    throw new AppException("未找到对应的父评论！parentCommentId:" + forumcomment.getParentCommentId());
                }

                if (StringUtils.hasText(parentForumcomment.getUserId())) {

                    if (parentForumcomment.getUserId().equals(vo.getUserId())) {
                        /**
                         * 对自己的评论进行评论不生成通知
                         */
                        logger.info("对自己的评论进行评论不生成通知！");
                        notice = null;
                    } else {
                        if (ForumServciceStatic.newsComment.equals(parentForumcomment.getMsgType())) {
                            logger.info("被回复的评论是对新闻的评论！");

                            CmfPostsDtlVo cmfPostsDtlVo = newsClient.getPostsDtlById(Long.valueOf(parentForumcomment.getForumMsgId())).getData();
                            if((null != cmfPostsDtlVo)
                                    &&(StringUtils.hasText(cmfPostsDtlVo.getTpl()))){
                                notice.setSourceType(cmfPostsDtlVo.getTpl());
                            }
                            notice.setNoticeType(ForumServciceStatic.newsCmtComentNotice);
                        } else {
                            notice.setNoticeType(ForumServciceStatic.cmtCommentNotice);
                        }
                        notice.setUserId(parentForumcomment.getUserId());
                        notice.setSourceId(parentForumcomment.getForumMsgId());
                        if(!StringUtils.hasText(notice.getSourceType())){
                            notice.setSourceType(parentForumcomment.getMsgType());
                        }
                        notice.setSourceDesc("回复了你的评论！");
                        forumNoticeService.insertSelective(notice);
                        logger.info("保存通知消息成功！id:" + notice.getForumNoticeId());
                    }
                }


                logger.info(parentForumcomment.getContent());

                if (null == parentForumcomment.getCommentCount()) {
                    logger.info("null == parentForumcomment.getCommentCount()！");
                    forumcommentMapper.updateCommentCount(parentForumcomment.getForumCommentId(), 1);
                    return true;
                }

                logger.info("parentForumcomment.getCommentCount():" + parentForumcomment.getCommentCount());
                forumcommentMapper.updateCommentCount(parentForumcomment.getForumCommentId(),
                        parentForumcomment.getCommentCount() + 1);

                if (StringUtils.hasText(parentForumcomment.getForumMsgId())) {
                    forummessageMapper.addCommentCount(parentForumcomment.getForumMsgId());
                }
                return true;
            }

            //对帖子进行评论
            if (ForumServciceStatic.msgComment.equals(vo.getMsgType())) {
                logger.info("对帖子进行评论！被评论的id：" + forumcomment.getForumMsgId());
                //评论的评论数+1
                Forummessage forummessage = forummessageMapper.selectByPrimaryKey(forumcomment.getForumMsgId());
                if (null == forummessage) {
                    throw new AppException("未找到对应的帖子！ForumMsgId:" + forumcomment.getForumMsgId());
                }

                if (forummessage.getUserId().equals(vo.getUserId())) {
                    logger.info("对自己的帖子进行评论不生成通知!");
                    notice = null;
                } else {
                    notice.setNoticeType(ForumServciceStatic.msgCommentNotice);
                    notice.setUserId(forummessage.getUserId());
                    notice.setSourceId(forummessage.getForumMsgId());
                    notice.setSourceType(forummessage.getMsgType());
                    notice.setSourceDesc("评论了你的帖子！");
                    forumNoticeService.insertSelective(notice);
                    logger.info("保存通知消息成功！id:" + notice.getForumNoticeId());
                }

                if (null == forummessage.getCommentCount()) {
                    forummessageMapper.updateCommentCount(forummessage.getForumMsgId(), 1);
                    return true;
                }

                forummessageMapper.updateCommentCount(forummessage.getForumMsgId(),
                        forummessage.getCommentCount() + 1);
                return true;
            }

            //对新闻进行评论
            if (ForumServciceStatic.newsComment.equals(vo.getMsgType())) {
                logger.info("对新闻进行评论，新闻的评论数+1！新闻id:" + vo.getMsgSourceId());
                newsClient.updateCommentCount(Long.valueOf(vo.getMsgSourceId()), "0");
                return true;
            }

            return true;
        } catch (Exception e) {
            logger.error("保存论坛评论异常：" + e);
            return false;
        }
    }

    @Transactional
    public Forumcomment selectById(String id) {
        if (!StringUtils.hasText(id)) {
            throw new AppException("id参数不允许为空");
        }
        try {
            return forumcommentMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            logger.error("保存论坛评论异常:" + e);
            return null;
        }
    }

    /**
     * 联合查询查出点赞记录
     *
     * @param userId
     * @param forumMsgId
     * @param rows
     * @param currentPage
     * @return
     * @author lid
     * @date 2017.10.18
     */
    @Transactional
    public PageData getCommentByMsgId(String userId, String forumMsgId, Integer rows, Integer currentPage) {
        if (!StringUtils.hasText(forumMsgId)) {
            throw new AppException("forumMsgId参数不允许为空");
        }
        try {
            PageData page = new PageData();

            List<Forumcomment> listForumcomment = forumcommentMapper.selectByForumMsgId(forumMsgId);
            Integer commentCount = listForumcomment.size();
            logger.info("commentCount:" + commentCount);

            Integer totalCount = commentCount;
            if ((StringUtils.hasText(userId)) && (null != listForumcomment)
                    && (0 < listForumcomment.size())) {

                List<String> listLikePointRecords = forumlikespointrecordService.getLikePointMsgsByUserId(userId);

                for (Forumcomment comment : listForumcomment) {
                    logger.info("comment.getForumCommentId():" + comment.getForumCommentId());

                    List<Forumcomment> listChildrenComment = comment.getListForumcomment();
                    if ((null != listChildrenComment)
                            && (0 < listChildrenComment.size())) {
                        logger.info("listChildrenComment.size():" + listChildrenComment.size());
                        totalCount = totalCount + listChildrenComment.size();
                        for (Forumcomment childComment : listChildrenComment) {
                            logger.info("childComment.getForumCommentId():" + childComment.getForumCommentId());
                            if (listLikePointRecords.contains(childComment.getForumCommentId())) {
                                childComment.setHasPraised(1);
                            }
                        }
                    }

                    if (listLikePointRecords.contains(comment.getForumCommentId())) {
                        comment.setHasPraised(1);
                    }
                }

            }

            /**
             * 手动分页
             */

            logger.info("totalCount:" + totalCount);

            page.setTotal(totalCount);

            Integer startIndex = rows * currentPage;
            Integer endIndex = rows * (currentPage + 1);
            if (startIndex > commentCount) {
                return null;
            }

            if (endIndex < commentCount) {
                List<Forumcomment> listResult = listForumcomment.subList(startIndex, endIndex);
                page.setRows(listResult);
                return page;
            }
            List<Forumcomment> listResult = listForumcomment.subList(startIndex, commentCount);
            page.setRows(listResult);

            return page;
        } catch (Exception e) {
            logger.error("获取论坛评论异常:" + e);
            return null;
        }
    }

    @Transactional
    public List<Forumcomment> selectByForumMsgId(String userId, String forumMsgId, Integer rows, Integer currentPage) {
        if (!StringUtils.hasText(forumMsgId)) {
            throw new AppException("forumMsgId参数不允许为空");
        }
        try {
            PageHelper.startPage(currentPage, rows);
            List<Forumcomment> listForumcomment = forumcommentMapper.selectByForumMsgId(forumMsgId);

            if ((StringUtils.hasText(userId)) && (null != listForumcomment)
                    && (0 < listForumcomment.size())) {
                logger.info("listForumcomment.size():" + listForumcomment.size());

                for (Forumcomment comment : listForumcomment) {
                    logger.info("comment.getForumCommentId():" + comment.getForumCommentId());

                    List<Forumcomment> listChildrenComment = comment.getListForumcomment();
                    if ((null != listChildrenComment)
                            && (0 < listChildrenComment.size())) {
                        logger.info("listChildrenComment.size():" + listChildrenComment.size());

                        for (Forumcomment childComment : listChildrenComment) {
                            logger.info("childComment.getForumCommentId():" + childComment.getForumCommentId());

                            int likesCount = forumlikespointrecordMapper.
                                    countByUserIdAndForumMsgId(userId, childComment.getForumCommentId());
                            logger.info("likesCount:" + likesCount);
                            if (0 < likesCount) {
                                childComment.setHasPraised(1);
                            }
                        }
                    }

                    int likesCount = forumlikespointrecordMapper.
                            countByUserIdAndForumMsgId(userId, comment.getForumCommentId());

                    logger.info("likesCount:" + likesCount);
                    if (0 < likesCount) {
                        comment.setHasPraised(1);
                    }
                }

            }
            return listForumcomment;
        } catch (Exception e) {
            logger.error("获取论坛评论异常:" + e);
            return null;
        }
    }

    @Transactional
    public void deleteById(String id) {
        if (!StringUtils.hasText(id)) {
            throw new AppException("id参数不允许为空");
        }

        logger.info("deleteById!id:" + id);

        try {
            //对应的帖子或者评论的评论数-1
            Forumcomment comment = forumcommentMapper.selectByPrimaryKey(id);

            if (StringUtils.hasText(comment.getParentCommentId())) {
                logger.info("删除对评论的评论！");
                Forumcomment parentForumcomment = forumcommentMapper.selectByPrimaryKey(comment.getParentCommentId());
                if (null == parentForumcomment) {
                    throw new AppException("未找到对应的父评论！parentCommentId:" + comment.getParentCommentId());
                }

                forumcommentMapper.updateCommentCount(parentForumcomment.getForumCommentId(),
                        parentForumcomment.getCommentCount() - 1);

                forumcommentMapper.deleteByPrimaryKey(id);
                return;
            }

            if (StringUtils.hasText(comment.getForumMsgId())) {
                logger.info("删除对帖子的评论！");

                Forummessage forummessage = forummessageMapper.selectByPrimaryKey(comment.getForumMsgId());
                if (null == forummessage) {
                    throw new AppException("未找到对应的帖子！ForumMsgId:" + comment.getForumMsgId());
                }

                logger.info("forummessage.getMsgContent():" + forummessage.getMsgContent());
                forummessageMapper.updateCommentCount(forummessage.getForumMsgId(),
                        forummessage.getCommentCount() - 1);

                forumcommentMapper.deleteByPrimaryKey(id);
                return;

            }
            forumcommentMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            logger.error("获取论坛评论异常:" + e);
            return;
        }
    }

    @Transactional
    public List<Forumcomment> getSelectForumcommentByPage(String content, String createDateS, String createDateE, Integer rows, Integer currentPage) {
        try {
            PageHelper.startPage(currentPage, rows);
            List<Forumcomment> listForumcomment = forumcommentMapper.getSelectForumcomment(content, createDateS, createDateE);
            return listForumcomment;
        } catch (Exception e) {
            logger.info("获取评论失败" + e);
            return null;
        }

    }

    @Transactional
    public List<Forumcomment> getSelectForumcomment(String content, String createDateS, String createDateE) {
        try {
            List<Forumcomment> listForumcomment = forumcommentMapper.getSelectForumcomment(content, createDateS, createDateE);
            return listForumcomment;
        } catch (Exception e) {
            logger.info("获取评论失败" + e);
            return null;
        }

    }


    /**
     * 统计我的评论的点赞总数
     *
     * @param userId
     * @return int
     * @author lid
     * @date 2017.7.11
     */
    @Transactional
    public int countLikePointsByUserId(String userId) {
        logger.info("countLikePointsByUserId");
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId参数为空！");
        }

        try {
            return forumcommentMapper.countLikePointsByUserId(userId);
        } catch (Exception e) {
            logger.info("我的评论的点赞总数失败" + e);
            return -1;
        }
    }

    @Transactional
    public int deleteCommentsByMsgId(String msgId) {
        if (!StringUtils.hasText(msgId)) {
            throw new AppException("msgId参数为空！");
        }

        try {
            return forumcommentMapper.deleteCommentsByMsgId(msgId);
        } catch (Exception e) {
            logger.info("删除评论失败" + e);
            return -1;
        }
    }
}
